import json
import urllib
import sys
import random
import time
import math

ulr = "http://coder9.selfip.com:8080/"

def get_distance2(x1,x2,y1,y2):
    return math.pow(x2-x1,2) + math.pow(y2-y1,2)

def main():
    actions = []
    player_number = create_new_player()['player_number']
    print 'I am player %s' % player_number
    turn = -1;
    
    while True:
        game_turn = get_turn()['turn']
        
        if turn < game_turn:
            data = get_player_view(player_number)
            space_items = data['view']
            
            think(player_number,space_items,actions)
            submit_actions(actions)
            actions = []
            turn = game_turn
        else:
            print 'still the same turn %s' % turn
        time.sleep(2)
        
        
def get_player_view(player_number):
    f = urllib.urlopen(ulr + "get_player_view/%s" % player_number)
    return json.loads(f.read())

def get_turn():
    f = urllib.urlopen(ulr + "get_turn")
    return json.loads(f.read())
        
def create_new_player():
    f = urllib.urlopen(ulr + "create_new_player")
    return json.loads(f.read())

def submit_actions(actions):
    print 'Submitting these actions'
    print "-" * 80
    for i in actions:
        print str(i)
    acts = json.dumps(actions)
    params = urllib.urlencode({'actions':acts})
    f = urllib.urlopen(ulr + "submit_actions", params)
    print f.read()
    print

def make_ship(base_idx,player_idx,x,y):
    return {'type':'create','what':'ship','base':base_idx,'player':player_idx,'x':x,'y':y}

def make_base(player_idx,x,y):
    return {'type':'create','what':'base','player':player_idx,'x':x,'y':y}

def move_ship_to(x,y,ship,in_range_idx,base_idx):
    x1 = ship['x']
    x2 = x
    y1 = ship['y']
    y2 = y
    
    if get_distance2(x1,x2,y1,y2) < math.pow(ship['speed'],2):
        print 'i can make it to the location'
        return {'type':'mine','miner':ship['idx'],'asteroid':in_range_idx,'base':base_idx}
    else:
        diff_x = x2 - x1
        diff_y = y2 - y1
        atan2 = math.atan2(diff_y, diff_x)
        cos = math.cos(atan2)
        sin = math.sin(atan2)
        new_x = int(round(x1 + cos * (ship['speed'] - 1)))
        new_y = int(round(y1 + sin * (ship['speed'] - 1)))
        print 'distance I can move %s' % math.sqrt(get_distance2(x1,new_x,y1,new_y))
        return {'type':'move','idx':ship['idx'],'x':new_x,'y':new_y}
    
def attack(attacker,target):
    print 'attacking !!!! %s' % target
    return {'type':'attack','atk':attacker,'tgt':target}

def think(player_idx,space_items,actions):
    bases = [i for i in space_items.values() if i['type'] == 'base' and i['player'] == player_idx]
    ships = [i for i in space_items.values() if i['type'] == 'ship' and i['player'] == player_idx]
    asteroids = [i for i in space_items.values() if i['type'] == 'asteroid']
    enemy = [i for i in space_items.values() if i['type'] == 'ship' and i['player'] != player_idx]
    ebases = [i for i in space_items.values() if i['type'] == 'base' and i['player'] != player_idx]             

    print 'thinking'
    
#    if len(bases) < 1:
#        x = random.randint(-200,200)
#        y = random.randint(-200,200)
#        a = make_base(player_idx,x,y)
#        actions.append(a)
#        return actions
    
    for b in bases:
        if b['ore'] > 10:
            print 'I have too much ore at base %s, ill make a ship' % b['idx']
            x = b['x'] + random.randint(0,5)
            y = b['y'] + random.randint(0,5)
            actions.append(make_ship(b['idx'],player_idx,x,y))
            
    for s in ships:
        #look for enemy base
        for eb in ebases:
            dis2 = get_distance2(s['x'],eb['x'],s['y'],eb['y'])
            range2 = math.pow(s['range'],2)
            if dis2 < range2:
                attack_action = attack(s['idx'],eb['idx'])
                actions.append(attack_action)
                break
            
        # look for enemy ship
        for e in enemy:
            dis2 = get_distance2(s['x'],e['x'],s['y'],e['y'])
            range2 = math.pow(s['range'],2)
            if dis2 < range2:
                attack_action = attack(s['idx'],e['idx'])
                actions.append(attack_action)
                break
            
        a = think_ship(s,asteroids,bases[0])
        if a != None:
            actions.append(a)
            
    
    return actions
        
def think_ship(ship,asteroids,base):
    #find closest asteroid
    closest = 99999999999999
    closest_asteroid = {'idx':0}
    x1 = ship['x']
    y1 = ship['y']
    
    for a in asteroids:
        dis2 = get_distance2(x1,a['x'],y1,a['y'])
        if dis2 < closest:
            closest_asteroid = a
            closest = dis2
    
    if closest_asteroid['idx'] != 0:
        return move_ship_to(closest_asteroid['x'],
                            closest_asteroid['y'],
                            ship,
                            closest_asteroid['idx'],
                            base['idx'])
    
    return None
    
def think_base(base):
    pass

if __name__ == '__main__':
    main()